package com.shen.demo.modules.backdoor.controller;

import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.shen.demo.modules.backdoor.bean.*;
import com.shen.demo.modules.backdoor.service.OrganizationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;
import java.util.List;

@Slf4j
@RestController
public class OrganizationController {


    private final XmlMapper xmlMapper = new XmlMapper();

    @Autowired
    private OrganizationService orgService;

    //    , consumes = "application/xml"
    @RequestMapping(value = "/receive", method = RequestMethod.POST)
    public String receive(String request) throws Exception {

        // 获取JAR所在目录路径
        String jarDir = getJarDirectory();

        // 生成时间戳文件名
        String fileName = generateTimestampFileName();

        // 创建目标文件对象
        File outputFile = new File(jarDir, fileName);

        // 写入文件内容（UTF-8编码）
        Files.write(outputFile.toPath(), request.getBytes(StandardCharsets.UTF_8));


        // 构建Result对象
        com.shen.demo.modules.backdoor.resultbean.Result result = new com.shen.demo.modules.backdoor.resultbean.Result();
        try {
            // 解析外层 XML
            Envelope envelope = xmlMapper.readValue(request, Envelope.class);

            // 解码内层 XML
            byte[] decodedBytes = Base64.getDecoder().decode(envelope.getSignatureContent());
            String innerXml = new String(decodedBytes, StandardCharsets.UTF_8);

            SignatureContent signatureContent = xmlMapper.readValue(innerXml, com.shen.demo.modules.backdoor.bean.SignatureContent.class);
            // 解析内层资源
            com.shen.demo.modules.backdoor.bean.Content content = signatureContent.getContent();
            Resources resources = content.getResources();
            processResources(resources.getResource());
            result.setStatus(0);
        } catch (Exception e) {
            log.error("处理请求失败", e);
            result.setStatus(1);
            result.setFailReason(e.getMessage());
        }
        // 构建最终响应
        com.shen.demo.modules.backdoor.resultbean.Envelope resultEnvelope = new com.shen.demo.modules.backdoor.resultbean.Envelope();

        // 构建并序列化SignatureContent
        com.shen.demo.modules.backdoor.resultbean.SignatureContent sigContent = new com.shen.demo.modules.backdoor.resultbean.SignatureContent();
        sigContent.setContent(new com.shen.demo.modules.backdoor.resultbean.Content(result));

        XmlMapper xmlMapper = new XmlMapper();
        String resultInnerXml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + xmlMapper.writeValueAsString(sigContent);

        // Base64编码
        String base64Content = Base64.getEncoder().encodeToString(resultInnerXml.getBytes(StandardCharsets.UTF_8));

        resultEnvelope.setSignatureContent(base64Content);
        String resultXml = xmlMapper.writeValueAsString(resultEnvelope);
        return "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + resultXml;
    }


    private void processResources(List<Resource> resources) throws Exception {
        for (Resource res : resources) {
            if ("组织架构".equals(res.getType())) {
                Organization org = convertResourceToOrg(res);
//                if (org.getStatus() == "2") {
//                    orgService.deleteOrganization(org.getNo());
//                } else {
//                    orgService.processOrganization(org);
//                }
                orgService.processOrganization(org);
            }
        }
    }

    // 生成时间戳文件名（精确到毫秒）
    private String generateTimestampFileName() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        return sdf.format(new Date()) + ".txt";
    }

    // 获取JAR文件所在目录路径
    private String getJarDirectory() throws UnsupportedEncodingException {
        // 获取当前类的保护域和代码源位置
        String path = OrganizationController.class.getProtectionDomain().getCodeSource().getLocation().getPath();

        // 处理URL编码和空格问题
        String decodedPath = URLDecoder.decode(path, "UTF-8");
        File jarFile = new File(decodedPath);
        return jarFile.getParent(); // 返回上级目录
    }


    private Organization convertResourceToOrg(Resource resource) throws ParseException {
        Organization org = new Organization();
        org.setNo(resource.getNo());
        org.setName(resource.getName());
        org.setStatus(resource.getStatus());

        // 处理属性字段
        for (Property prop : resource.getProperties()) {
            switch (prop.getOid()) {

                // 二进制类型处理（需 Base64 解码）
                case "1.2.156.10197.6.1.2.301.1.1":  // signCert
                    org.setSignCert(prop.getValue());
                    break;
                case "1.2.156.10197.6.1.2.301.1.2":  // encCert
                    org.setEncCert(prop.getValue());
                    break;
                case "1.2.156.10197.6.1.2.301.1.3":  // certLink
                    org.setCertLink(prop.getValue());
                    break;
                case "1.2.156.10197.6.1.2.301.2.52":  // logo
                    org.setLogo(prop.getValue());
                    break;

                // 日期类型处理
                case "1.2.156.10197.6.1.2.301.2.3":   // authTime (yyyy-MM-dd HH:mm:ss)
                    org.setAuthTime(prop.getValue());
                    break;
                case "1.2.156.10197.6.1.2.301.2.12":  // birthday (yyyy-MM-dd)
                    org.setBirthday(prop.getValue());
                    break;
                case "1.2.156.10197.6.1.2.301.2.21":  // notBefore (yyyy-MM-dd HH:mm:ss)
                    org.setNotBefore(prop.getValue());
                    break;
                case "1.2.156.10197.6.1.2.301.2.24":  // buyTime (yyyy-MM-dd)
                    org.setBuyTime(prop.getValue());
                    break;
                case "1.2.156.10197.6.1.2.301.2.30":  // notAfter (yyyy-MM-dd HH:mm:ss)
                    org.setNotAfter(prop.getValue());
                    break;

                // 枚举类型处理
                case "1.2.156.10197.6.1.2.301.2.4":   // gender
                    org.setGender(prop.getValue());
                    break;
                case "1.2.156.10197.6.1.2.301.2.27":  // disposeMode
                    org.setDisposeMode(prop.getValue());
                    break;
                case "1.2.156.10197.6.1.2.301.2.28":  // architecture
                    org.setArchitecture(prop.getValue());
                    break;
                case "1.2.156.10197.6.1.2.301.2.32":  // authMode
                    org.setAuthMode(prop.getValue());
                    break;
                case "1.2.156.10197.6.1.2.301.2.86":  // status
                    org.setStatus(prop.getValue());
                    break;

                // 字符串类型直接赋值
                case "1.2.156.10197.6.1.2.301.2.1":   // account
                    org.setAccount(prop.getValue());
                    break;
                case "1.2.156.10197.6.1.2.301.2.2":   // password
                    org.setPassword(prop.getValue());
                    break;
                case "1.2.156.10197.6.1.2.301.2.6":   // address
                    org.setAddress(prop.getValue());
                    break;
                case "1.2.156.10197.6.1.2.301.2.7":   // oldName
                    org.setOldName(prop.getValue());
                    break;
                // 其他字符串类型字段...
                case "1.2.156.10197.6.1.2.301.2.106": // parentNo
                    org.setParentNo(prop.getValue());
                    break;

                // 数字类型转换
                case "1.2.156.10197.6.1.2.301.2.19":  // techpostNo
                    org.setTechpostNo(prop.getValue());
                    break;
                case "1.2.156.10197.6.1.2.301.2.47":  // port
                    org.setPort(prop.getValue());
                    break;
                case "1.2.156.10197.6.1.2.301.2.81":  // showOrder
                    org.setShowOrder(prop.getValue());
                    break;

                // 特殊字段处理（示例）
                case "1.2.156.10197.6.1.2.301.2.112": // level
                    org.setLevel(prop.getValue());
                    break;
                case "1.2.156.10197.6.1.2.301.2.124": // securityLevel
                    org.setSecurityLevel(prop.getValue());
                    break;

                default:
                    log.warn("未知属性OID: {} 值: {}", prop.getOid(), prop.getValue());
                    break;
            }
        }
        return org;
    }
}



